GetFileAttributes <- function(raw.data) {
  file.attr.begin <- which(raw.data[,1]=="File Attributes");
  file.attributes <- raw.data[(file.attr.begin+1):(file.attr.begin+7),];
  return(file.attributes);
}

GetLaneAttributes <- function(raw.data) {
  lane.attr.begin <- which(raw.data[,1]=="Lane Attributes");
  lane.attributes <- raw.data[(lane.attr.begin+1):(lane.attr.begin+7),];

  return(lane.attributes);
}

GetReporterCounts <- function(raw.data) {
  reporter.cnts.begin <- which(raw.data[,1]=="Reporter Counts");
  reporter.counts <- raw.data[(reporter.cnts.begin+1):nrow(raw.data),];

#  browser();
  
#  reporter.counts <- apply(reporter.counts, c(1,2),as.numeric);

  return(reporter.counts);
}

ReadSampleInfo <- function(filename) {
  sample <- read.table(filename, header=TRUE, row.names=1, sep="\t", colClasses='character', fill=TRUE);
  return(sample);
}

ReadNCounter <- function(filename, pData = NULL, nlanes=12) {
  ncol = nlanes+3;
  raw.data <- matrix(scan(filename, what='raw', sep='\t'),ncol=ncol, byrow=TRUE);

  file.attributes <- GetFileAttributes(raw.data);
  lane.attributes <- GetLaneAttributes(raw.data);
  reporter.counts <- GetReporterCounts(raw.data);

  if(!is.null(pData)) {
    pheno.data <- new('AnnotatedDataFrame', data=pData);
  } else {
    pheno.data <- NULL;
  }

  ## set up feature data
  fData <- data.frame('Code Class' = reporter.counts[-1,1],
                      'Accession' = reporter.counts[-1,3],
                      row.names = make.names(reporter.counts[-1,2], unique=TRUE));
  
  feature.data <- new('AnnotatedDataFrame', data = fData);

  ## set up expression data
  exprs <- reporter.counts[-1,4:ncol(reporter.counts)];
  exprs <- apply(exprs, c(1,2),as.numeric);
  
  colnames(exprs) <- file.attributes[1,-c(1,2,3)];
  rownames(exprs) <- make.names(reporter.counts[-1,2], unique=TRUE);
  
  ncounter.set <- new('NCounterSet', featureData = feature.data,
                      exprs = exprs, phenoData = pheno.data);
  ##ncounter.set <- new('NCounterSet', exprs = exprs);

  return(ncounter.set);
}
